#include "widget.h"
#include "deletehistorydialog.h"
#include "ui_widget.h"
#include<QFile>

// 新增：网络请求线程实现
NetworkThread::NetworkThread(const QByteArray &data, QObject *parent)
    : QThread(parent), m_data(data) {}

void NetworkThread::run() {
    QNetworkAccessManager manager;
    QNetworkRequest request(QUrl("https://api.deepseek.com/chat/completions"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setRawHeader("Authorization", "Bearer sk-080944a2ff90454c812ed695b0575da0");

    QNetworkReply *reply = manager.post(request, m_data);
    // 用信号槽替代 waitForFinished
    connect(reply, &QNetworkReply::finished, [this, reply]() {
        if (reply->error() == QNetworkReply::NoError) {
            emit responseReady(reply->readAll());
        } else {
            emit errorOccurred(reply->errorString());
        }
        reply->deleteLater(); // 释放资源
    });

    // 启动线程事件循环（确保信号槽执行）
    exec();
}

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setupTrayIcon();

    //加载qss样式表
    QFile file(":/qss/style.qss");
    if (file.open(QFile::ReadOnly | QFile::Text)) {

        setStyleSheet(file.readAll());
        file.close();
    }

    setupDatabase();  //初始化数据
     m_isLocked=false;
    ui->progressBar->setRange(0,100); //进度条
    ui->progressBar->setValue(0);

    networkmanger=new QNetworkAccessManager(this);   //初始化网络接收器
    loadHistory();    //加载历史记录

    //初始化计时器
    timer=new QTimer(this);
    connect(timer,&QTimer::timeout,this,&Widget::updateTimerLabel);

    //历史记录列表
    ui->listWidget_history->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->listWidget_history,&QListWidget::customContextMenuRequested,this,&Widget::showDeletelistContextMenu);
    ui->listWidget_history->setSelectionMode(QAbstractItemView::ExtendedSelection);
}

Widget::~Widget()
{

    delete ui;
}



void Widget:: setupDatabase()    //初始化数据库链接
{
    QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("ai_assistant.db");
    if(!db.open())
    {
        QMessageBox::critical(this,"error","open database fail"+db.lastError().text());
        return;
    }
    //创建表
    QSqlQuery query;
    query.exec("create table if not exists history("
               "id integer primary key autoincrement,"
               "question TEXT,"
               "answer TEXT"
               ")");
    //创建新表（记录删除历史）
    query.exec("CREATE TABLE IF NOT EXISTS deleted_history("
                    "deleted_id INTEGER PRIMARY KEY AUTOINCREMENT,"   //自增主键，唯一标识每条删除记录
                    "original_id INTEGER NOT NULL,"    //原记录的 ID
                    "question TEXT NOT NULL,"         //被删除的问题
                    "answer TEXT,"                          //被删除的答案
                    "deleted_date DATETIME NOT NULL,"
                    "FOREIGN KEY (original_id) REFERENCES history(id)”)");      //时间

}

void Widget::handleResponse(const QByteArray &data) {
    // 原 onResponseRecieved 中的解析逻辑（移除网络相关代码）
    QJsonDocument jsonresponse = QJsonDocument::fromJson(data);
    QJsonObject jsonObj = jsonresponse.object();

    if (jsonObj.contains("choices")) {
        QJsonArray choices = jsonObj["choices"].toArray();
        if (!choices.empty()) {
            QString assistantResonse = choices[0].toObject()["message"].toObject()["content"].toString();
            ui->textEdit_reponse->setText("Xiao ming find answer :" + assistantResonse);
            saveAnswer(assistantResonse);
        }
    }

    // 更新进度条和计时器（与原逻辑一致）
    ui->progressBar->setValue(100);
    timer->stop();
    qint64 elapsedSeconds = elapsedTimer.elapsed() / 1000;
    ui->label_time->setText("Time elapsed: " + QString::number(elapsedSeconds) + " seconds");
}

void Widget::saveAnswer(const QString &answer)     //保存提问记录
{
    QSqlQuery query;
    query.prepare("update history set answer=:answer where id=(select max(id) from history)");
    query.bindValue(":answer",answer);
    if(!query.exec())
    {
        QMessageBox::critical(this,"error","fail to save answer "+query.lastError().text());
        return;
    }
}

void Widget::loadHistory()   //加载历史记录
{
    QSqlQuery query("select id ,question from history ");
    while(query.next())
    {
        int id=query.value(0).toInt();
        QString question=query.value(1).toString();
        QListWidgetItem *item=new QListWidgetItem(question);
        item->setData(Qt::UserRole,id);       //存储id到userrole
        ui->listWidget_history->addItem(item);
    }
}

void Widget::on_listWidget_history_itemClicked(QListWidgetItem *item)  //历史记录点击
{
    QString text=item->text();
    QString answer=getAnswerForQuestion(text);
        ui->textEdit_reponse->clear();
        ui->textEdit_reponse->append(answer);
}

QString Widget::getAnswerForQuestion(const QString& question)     //获取历史回答
{
    QSqlQuery query;
    query.prepare("SELECT answer FROM history WHERE question=:question");
    query.bindValue(":question",question);
    if(query.exec()&&query.next())
    {
        return query.value(0).toString();
    }
    return "not find answer";
}

bool Widget::saveQuestion(const QString&question) //保存提问记录
{
    QSqlQuery query;
    query.prepare("INSERT INTO history (question) VALUES (:question)");

    query.bindValue(":question",question);
    if(!query.exec())
    {
        QMessageBox::warning(this,"error","Fail to save question:"+query.lastError().text());
        return false;
    }
    else
    {
        int newid=query.lastInsertId().toInt();
        QListWidgetItem *newitem=new QListWidgetItem(question);
        newitem->setData(Qt::UserRole,newid);
        ui->listWidget_history->addItem(newitem);
    }
    return true;
}
//左侧列表右击显示
void Widget::showDeletelistContextMenu(const QPoint &pos)
{
    QList<QListWidgetItem*> selectedItems=ui->listWidget_history->selectedItems();
    if(selectedItems.empty())
    {
        return;
    }
    QMenu contextMenu(this);
    QAction *deleteAction=new QAction("删除历史记录",this);

    //连接删除动作
    connect(deleteAction,&QAction::triggered,this,[this,selectedItems](){
        QMessageBox::StandardButton reply=QMessageBox::warning(this,"删除确认","确定要删除吗，无法恢复",QMessageBox::Yes|QMessageBox::No);
        if(reply!=QMessageBox::Yes)
            return;

        //检查数据库连接是否正常
        QSqlDatabase db=QSqlDatabase::database();
        if(!db.isOpen())
        {
            QMessageBox::critical(this,"error","数据库连接异常");
            return;
        }

        bool transactionOk=true;
        QVector<int>deletedids;       //记录删除id，日志需要
        db.transaction();      //开启事务
        for(QListWidgetItem *item:selectedItems)
        {
            //空值直接跳过
            if(!item)
                continue;
            int recordid =item->data(Qt::UserRole).toInt(); //获取该项关联的数据库id
            //先查原始记录（用于记录）
            QSqlQuery selectQuery;
            selectQuery.prepare("SELECT question,answer FROM history WHERE id=?");
            selectQuery.addBindValue(recordid);
            if(!selectQuery.exec()||!selectQuery.next())
            {
                transactionOk=false;
                QMessageBox::critical(this,"error",QString("无法读取记录：%1").arg(selectQuery.lastError().text()));
                break;
            }

            //获取问题和答案内容
            QString question =selectQuery.value(0).toString();
            QString answer =selectQuery.value(1).toString();

            QSqlQuery insertQuery;
            insertQuery.prepare("INSERT INTO deleted_history"
                                "(original_id,question,answer,deleted_data)"
                                "VALUES(?,?,?,?)");
            insertQuery.addBindValue(recordid);
            insertQuery.addBindValue(question);
            insertQuery.addBindValue(answer);
            insertQuery.addBindValue(QDateTime::currentDateTime());

            if(!insertQuery.exec())
            {
                transactionOk=false;
                QMessageBox::critical(this,"error",QString("系统提示：备份失败：%1").arg(insertQuery.lastError().text()));
                break;
            }

            //删除原始记录
            QSqlQuery deleteQuery;
            deleteQuery.prepare("DELETE FROM history WHERE id=?");
            deleteQuery.addBindValue(recordid);

            if(!deleteQuery.exec())
            {
                transactionOk=false;
                QMessageBox::critical(this,"error",QString("系统提示：删除失败：%1").arg(deleteQuery.lastError().text()));
                break;
            }
            deletedids.append(recordid);  //记录删除id
            //根据事务执行情况提交或回滚
            if(transactionOk&&db.commit())
            {
                qDeleteAll(selectedItems);      //释放内容并移除项
                QMessageBox::information(this,"successed","系统提示，已成功成功！");
            }
            else
            {
                db.rollback();
                QMessageBox::critical(this,"error","系统提示，操作已回滚！");
            }
        }
    });

    contextMenu.addAction(deleteAction);
    contextMenu.exec(ui->listWidget_history->mapToGlobal(pos));        //在鼠标位置显示菜单
}

// 从数据库获取密码哈希
QByteArray Widget::getStoredPasswordHash()
{
    QSqlQuery query("SELECT password_hash FROM security_settings WHERE id = 1");
    if (query.exec() && query.next())
    {
        return query.value(0).toByteArray();
    }
    else
    {
        qCritical() << "获取密码哈希失败：" << query.lastError().text();
        return QByteArray(); // 返回空表示失败
    }
}
//slots

void Widget::updateTimerLabel()//更新耗时时间
{
     qint64 elapsedSeconds=elapsedTimer.elapsed()/1000;
    ui->label_time->setText("Timer elapsed:"+QString::number(elapsedSeconds)+"seconds");
}

void Widget::onDownloadProgress(qint64 bytesReceived,qint64 bytesTotal)     //更新进度条
{
    if(bytesReceived>0)
    {
        int progress=static_cast<int>((bytesReceived*100)/bytesTotal);
        ui->progressBar->setValue(progress);
    }
}
//

void Widget::on_pushButton_exit_clicked()
{
    QApplication::quit();
}


void Widget::on_pushButton_commit_clicked() {
    ui->textEdit_reponse->setText("A are searching for answer...... ,please patiently wait.\n");
    QString userInput = ui->lineEdit_question->text().trimmed();
    if (userInput.isEmpty()) {
        QMessageBox::critical(this, "error", "input cannot be empty!!!");
        return;
    }
    ui->lineEdit_question->clear();

    // 构建请求数据
    QJsonObject requestData;
    requestData["model"] = "deepseek-chat";
    requestData["stream"] = false;
    QJsonArray messages;
    // 添加系统和用户消息...
    //添加系统角色消息
    QJsonObject systemMessage;
    systemMessage["role"]="system";
    systemMessage["content"]="You are a helpful assistant.";
    //添加到消息数组
    messages.append(systemMessage);

    //添加用户角色信息
    QJsonObject userMessage;
    userMessage["role"]="user";
    userMessage["content"] =userInput;   //内容是用户输入
    messages.append(userMessage);

    requestData["messages"] = messages;
    QByteArray data = QJsonDocument(requestData).toJson();

    NetworkThread *thread = new NetworkThread(data, this);

    // 连接信号到主线程处理函数
    connect(thread, &NetworkThread::responseReady, this, &Widget::handleResponse);
    connect(thread, &NetworkThread::errorOccurred, this, [this](const QString &error) {
        ui->textEdit_reponse->append("Error: " + error);
        ui->progressBar->setValue(100);
        timer->stop();
    });

    // 自动释放线程资源
    connect(thread, &QThread::finished, thread, &QObject::deleteLater);

    thread->start(); // 启动子线程

    // 原逻辑：保存提问、更新进度条等
    saveQuestion(userInput);
    ui->progressBar->setValue(0);
    elapsedTimer.start();
    timer->start(1000);
}

void Widget::on_pushButton_administ_clicked()      //管理员
{

    //是否被锁定
    if(m_isLocked)
    {
        QMessageBox::warning(this,"登陆锁定","系统提示：密码错误次数太多，请稍后再试！！！",QMessageBox::Ok);
        return;
    }
    //弹出密码输入对话框
    bool ok;
    QString password=QInputDialog::getText(this,tr("管理员登录"),tr("系统提示:请输入密码:"),QLineEdit::Password,"",&ok);
    //用户取消输入
    if(!ok)
    {
        return;
    }
    //计算存贮的密码SHA-256
    QByteArray inputHash=QCryptographicHash::hash(password.toUtf8(),QCryptographicHash::Sha256);
    QString stringHex=inputHash.toHex();

    QByteArray storeHash=getStoredPasswordHash();

    if(stringHex==storeHash)
    {
        m_loginAttempts=0;
        DeleteHistoryDialog *dialog=new DeleteHistoryDialog(this);
        dialog->setAttribute(Qt::WA_DeleteOnClose);         // 设置对话框在关闭时自动释放内存，避免内存泄漏。
        dialog->exec();                                          //以模态方式显示对话框（用户必须先关闭对话框才能继续操作主窗口）。
    }
    else
    {
        m_loginAttempts++;
        if(m_loginAttempts>=3)
        {
            m_isLocked=true;
            //30s之后自动解锁
            if(!m_unlockTimer)
            {
                m_unlockTimer=new QTimer(this);
                connect(m_unlockTimer,&QTimer::timeout,[this]{
                    m_isLocked=false;
                    m_loginAttempts=0;
                    m_unlockTimer->deleteLater();
                    m_unlockTimer=nullptr;
                });
            }

            //30之后解锁
            m_unlockTimer->start(30000);
            QMessageBox::warning(this,"登录锁定","系统提示：密码错误次数过多，请30秒之后再试！！！",QMessageBox::Ok);
        }
        else
        {
            QMessageBox::information(this,"登录锁定",tr("系统提示：剩余尝试次数：%1").arg(3-m_loginAttempts),QMessageBox::Ok);

        }
    }
}

void Widget::closeEvent(QCloseEvent *event)
{
    // 隐藏主窗口，而非退出程序
    hide();
    event->ignore(); // 忽略默认关闭行为
}

void Widget::setupTrayIcon()
{
    // 1. 创建托盘图标（替换为你的图标资源）
    trayIcon = new QSystemTrayIcon(QIcon(":/images/title.png"), this);

    // 2. 创建托盘菜单
    trayMenu = new QMenu(this);

    // 菜单 - 显示主窗口
    QAction *showAction = trayMenu->addAction("显示窗口");
    connect(showAction, &QAction::triggered, this, &Widget::show);

    // 菜单 - 快速提问（关联现有逻辑）
    QAction *quickAskAction = trayMenu->addAction("快速提问");

    connect(quickAskAction, &QAction::triggered, [this]() {
        QString question = QInputDialog::getText(this, "快速提问", "请输入问题：");
        if (!question.isEmpty()) {
            ui->lineEdit_question->setText(question);
            on_pushButton_commit_clicked(); // 复用已有提交逻辑
        }
    });

    // 菜单 - 退出程序
    QAction *quitAction = trayMenu->addAction("退出程序");
    connect(quitAction, &QAction::triggered, qApp, &QApplication::quit);

    // 设置托盘菜单
    trayIcon->setContextMenu(trayMenu);

    // 3. 托盘交互：单击显示/隐藏窗口
    connect(trayIcon, &QSystemTrayIcon::activated, this, &Widget::onTrayIconActivated);

    // 4. 显示托盘（必须调用）
    trayIcon->show();
}

// 托盘点击事件：单击切换窗口显示
void Widget::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
    if (reason == QSystemTrayIcon::Trigger) { // 鼠标单击
        if (isVisible()) {
            hide(); // 隐藏窗口
        } else {
            show(); // 显示窗口
            activateWindow(); // 激活窗口
        }
    }
}













//
